﻿using System;
using System.Linq;
using System.Net.NetworkInformation;
using Lasalara.Model;
using Microsoft.Phone.Net.NetworkInformation;
using RestSharp;

namespace Lasalara.ViewModel
{
    public class StudyViewModel : GlobalViewModel
    {
        /// <summary>
        /// Send question
        /// </summary>
        /// <param name="user">User that send's question</param>
        /// <param name="question">Proposed question</param>
        /// <param name="answer">Proposed answer</param>
        /// <param name="callback">Callback method</param>
        public void SendQuestionWebRequest(User user, string question, string answer,
                                           Action<RestResponse, User> callback)
        {
            var client = new RestClient(App.BaseUrl);
            var request = new RestRequest(Method.POST)
                              {
                                  Resource = "posequestion",
                                  RequestFormat = DataFormat.Json
                              };
            request.AddParameter("ck", user.CurrentChapter.ChapterKey);
            request.AddParameter("uk", user.UserKey);
            request.AddParameter("question", question);
            request.AddParameter("answer", answer);
            client.ExecuteAsync(request, (response) => callback(response as RestResponse, user));
        }

        /// <summary>
        /// Validate if question proposal can be sent.
        /// </summary>
        /// <param name="question">Proposed question</param>
        public static bool ValidateQuestionProposal(string question)
        {
            if (!string.IsNullOrEmpty(question.Trim()))
            {
                if (DeviceNetworkInformation.IsNetworkAvailable)
                {
                    return true;
                }
                ShowToast(AppResources.Error, AppResources.CannotProposeWithNoInternet);
            }
            else
            {
                ShowToast(AppResources.Error, AppResources.EnterQuestionAndAnswer);
            }
            return false;
        }

        /// <summary>
        /// Set all questions as not answered and progress to 0
        /// </summary>
        public static void ResetProgress(User currentUser)
        {
            currentUser.CurrentChapter.CurrentQuestion = null;
            currentUser.CurrentChapter.Progress = 0;
            foreach (var question in currentUser.CurrentChapter.Questions)
            {
                question.AnsweredDate = DateTime.Now.AddDays(-1);
                question.AnswerCount = 0;
            }
        }
    }
}